#include "checker.h"
#include <QtCore/QDebug>

Checker::Checker(QString email, QString password)
{
    // init
    lastMessage = "";
    notShowCount = 0;
    // creating popup
    m_popup = new Popup("");
    // creating trayicon
    m_trayicon = new TrayIcon();
    connect(m_trayicon, SIGNAL(showOptions()), this, SLOT(showOptions()));
    connect(m_trayicon, SIGNAL(iconClicked()), this, SLOT(trayIconClicked()));
    connect(m_trayicon, SIGNAL(quit()), this, SLOT(quit()));
    // creating settings
    m_options = new Options(QDir::homePath()+"/.kcheckvkontakte");
    m_options->load();
    m_options->updateValues(email, password);
    if ((m_options->settings.email == "") || (m_options->settings.password == ""))
        showOptions();
    connect(m_options, SIGNAL(optionsChanged()), this, SLOT(reloadSettings()));
    // creating client
    m_client = new Client(m_options->settings.email, m_options->settings.password);
    reloadSettings();
    connect(m_client, SIGNAL(error(QString)), this, SLOT(onError(QString)));
    connect(m_client, SIGNAL(messagesCount(int)), this, SLOT(onCountReceived(int)));
}

Checker::~Checker()
{
    delete m_popup;
    delete m_options;
    delete m_client;
    m_timer->stop();
    delete m_timer;
}

void Checker::run()
{
    m_timer = new QTimer();
    m_timer->singleShot(100, this, SLOT(onTimer()));
}

void Checker::reloadSettings()
{
    qDebug() << "Reloading settings";
    // reloding
    m_client->setAuthInfo(m_options->settings.email, m_options->settings.password);
    m_client->setProxyInfo(m_options->settings.useProxy, m_options->settings.proxyHost, m_options->settings.proxyPort,
                           m_options->settings.useProxyAuth, m_options->settings.proxyUser, m_options->settings.proxyPass);
}

void Checker::onTimer()
{
    qDebug() << "Timer event!";
    m_client->check();
    m_timer->singleShot(m_options->settings.checkTime*1000, this, SLOT(onTimer()));
}

void Checker::onError(QString message)
{
    showPopup(message);
}

void Checker::onCountReceived(int count)
{
    QString message = "";
    if (count == 0)
        message = tr("No unread messages");
    else
        message = tr("%n unread message(s)", "", count);
    showPopup(message);
}

void Checker::showPopup(QString message, bool force)
{
    qDebug() << "Show popup: " << message;
    if ((lastMessage != message || notShowCount >= 5 || force) && (!m_popup->running))
    {
        qDebug() << "POP-UP: " << message;
        delete m_popup;
        m_popup = new Popup(message);
        m_popup->run();
        notShowCount = 0;
    }
    else
        notShowCount++;
    lastMessage = message;
}

void Checker::trayIconClicked()
{
    showPopup(lastMessage, true);
}

void Checker::showOptions()
{
    m_options->showDialog();
}

void Checker::quit()
{
    QApplication::quit();
}
